<?php
import("ORG.Util.Function");
import("@.Org.Utils");
import("@.Org.FavourableTool");


class FavourableAction extends CommonAction{	
	
	public function _initialize(){
		parent::_initialize();				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	
	/**
	 * 优惠列表
	 * Enter description here ...
	 */
	public function favourable_list(){
			
	    $this->assign('favourable_list', $list['item']);
	
	    /*$sort_flag  	= 	sort_flag($list['filter']);
	    $this->assign($sort_flag['tag'], $sort_flag['img']); // 默认排序字段 */
	    
	    $sql_favourable_list		= 	get_sql_favourable_list();
	    
	    $param = array(
				'result'	=> $sql_favourable_list,			//分页用的数组或sql
				'listvar'	=> 'favourable_list',				//分页循环变量
				'listRows'	=> 10,							//每页记录数
				//'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'	=> 'content',	    			//ajax更新内容的容器id，不带#
				'pagesId'	=> 'page',						//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'	=> 'Favourable:favourable_list',		//ajax更新模板
		);		
	    $this->page_favourable_list($param);
		$this->display();
	}
	
	/**
	 * 优惠列表分页
	 * Enter description here ...
	 * @param unknown_type $param
	 */
	public function page_favourable_list($param){
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		//========================================格式化数据
	    $list 					= 	array();    
	    foreach($voList as $row){
	    	$row['start_time']  = local_date('Y-m-d H:i', $row['start_time']);
	        $row['end_time']    = local_date('Y-m-d H:i', $row['end_time']);
	        $list[] = $row;
	    }
	    $voList					=	$list;
		//========================================格式化数据
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * 添加优惠
	 * Enter description here ...
	 */
	public function add_favourable(){
	
		$CommonModel			=	new CommonModel();
	    /* 是否添加 */
	    $this->assign('form_action', 	'insert');
	    $this->assign('action', 		'add_favourable_ok');
	    $this->assign('help_open', 		1);
	
	    /* 初始化、取得优惠活动信息 */
        $favourable = array(
            'act_id'        => 0,
            'act_name'      => '',
            'start_time'    => date('Y-m-d', time() + 86400),
            'end_time'      => date('Y-m-d', time() + 4 * 86400),
            'user_rank'     => '',
            'act_range'     => FAR_ALL,
            'act_range_ext' => '',
            'min_amount'    => 0,
            'max_amount'    => 0,
            'act_type'      => FAT_GOODS,
            'act_type_ext'  => 0,
            'gift'          => array()
        );
	   
	    $this->assign('favourable', $favourable);
	
	    /* 取得用户等级 */
	    $user_rank_list 		= 	array();
	    $user_rank_list[] 		= 	array(
	        'rank_id'   => 0,
	        'rank_name' => L('not_user'),
	        'checked'   => strpos(',' . $favourable['user_rank'] . ',', ',0,') !== false
	    );
	    $sql 					= 	"SELECT rank_id, rank_name FROM " . 'ybr_user_rank';
	    $res 					= 	$CommonModel->query($sql);
	    foreach($res as $row){
	    	$row['checked'] 	= 	strpos(',' . $favourable['user_rank'] . ',', ',' . $row['rank_id']. ',') !== false;
	        $user_rank_list[] 	= 	$row;
	    }
	    
	    $this->assign('user_rank_list', $user_rank_list);
	
	    /* 取得优惠范围 */
	    $act_range_ext = array();
	    if ($favourable['act_range'] != FAR_ALL && !empty($favourable['act_range_ext'])){
	        if ($favourable['act_range'] == FAR_CATEGORY){
	            $sql 			= 	"SELECT cat_id AS id, cat_name AS name FROM " . 'ybr_category' .
	                				" WHERE cat_id " . db_create_in($favourable['act_range_ext']);
	        }
	        elseif ($favourable['act_range'] == FAR_BRAND){
	            $sql = "SELECT brand_id AS id, brand_name AS name FROM " . 'ybr_brand' .
	                " WHERE brand_id " . db_create_in($favourable['act_range_ext']);
	        }
	        else{
	            $sql 			= 	"SELECT goods_id AS id, goods_name AS name FROM " . 'ybr_goods' .
	                				" WHERE goods_id " . db_create_in($favourable['act_range_ext']);
	        }
	        $act_range_ext 		= 	$CommonModel->query($sql);
	    }
	    $this->assign('act_range_ext', $act_range_ext);
		
		$this->display('favourable_info');
	}
	
	/**
	 * 处理添加优惠
	 * Enter description here ...
	 */
	public function add_favourable_ok(){
	
		import("@.Plugs.Exchange");
				
		$CommonModel		=	new CommonModel();		
		$exc 				= 	new exchange('ybr_favourable_activity', $CommonModel, 'act_id', 'act_name');
			
	    /* 检查名称是否重复 */
	    $act_name 			= 	sub_str($_POST['act_name'], 255, false);
	    if (!$exc->is_only('act_name', $act_name, intval($_POST['id']))){
	        $this->error(L('act_name_exists'));
	    }
	
	    /* 检查享受优惠的会员等级 */
	    if (!isset($_POST['user_rank'])){
	        $this->error(L('pls_set_user_rank'));
	    }
	
	    /* 检查优惠范围扩展信息 */
	    if (intval($_POST['act_range']) > 0 && !isset($_POST['act_range_ext'])){
	        //sys_msg($_LANG['pls_set_act_range']);
	        $this->error(L('pls_set_act_range'));	    
	    }
	
	    /* 检查金额上下限 */
	    $min_amount 		= 	floatval($_POST['min_amount']) >= 0 ? floatval($_POST['min_amount']) : 0;
	    $max_amount 		= 	floatval($_POST['max_amount']) >= 0 ? floatval($_POST['max_amount']) : 0;
	    if ($max_amount > 0 && $min_amount > $max_amount){
	        $this->error(L('amount_error'));	    
	    }
	
	    /* 取得赠品 */
	    $gift 				= 	array();
	    if (intval($_POST['act_type']) == FAT_GOODS && isset($_POST['gift_id'])){
	        foreach ($_POST['gift_id'] as $key => $id){
	            $gift[] 	= 	array('id' => $id, 'name' => $_POST['gift_name'][$key], 'price' => $_POST['gift_price'][$key]);
	        }
	    }
	
	    /* 提交值 */
	    $favourable = array(
	        'act_id'        => intval($_POST['id']),
	        'act_name'      => $act_name,
	        'start_time'    => local_strtotime($_POST['start_time']),
	        'end_time'      => local_strtotime($_POST['end_time']),
	        'user_rank'     => isset($_POST['user_rank']) ? join(',', $_POST['user_rank']) : '0',
	        'act_range'     => intval($_POST['act_range']),
	        'act_range_ext' => intval($_POST['act_range']) == 0 ? '' : join(',', $_POST['act_range_ext']),
	        'min_amount'    => floatval($_POST['min_amount']),
	        'max_amount'    => floatval($_POST['max_amount']),
	        'act_type'      => intval($_POST['act_type']),
	        'act_type_ext'  => floatval($_POST['act_type_ext']),
	        'gift'          => serialize($gift)
	    );
	    
	    if ($favourable['act_type'] == FAT_GOODS){
	        $favourable['act_type_ext'] = round($favourable['act_type_ext']);
	    }
	
	    /* 保存数据 */
        $CommonModel->autoExecute('favourable_activity', $favourable, 'INSERT');
        $favourable['act_id'] 		= 	$CommonModel->insert_id();
	
        admin_log($favourable['act_name'], 'add', 'favourable'); // 记录操作
	
	    /* 清除缓存
	    clear_cache_files(); */
	
	    /* 提示信息 */
        $this->success("操作成功",U('favourable/favourable_list'));
	}
	
	/**
	 * 搜索
	 * Enter description here ...
	 */
	public function search(){
		
		$CommonModel		=	new CommonModel();
		
	    $filter 			= 	$_GET['JSON'];
	    $filter['keyword'] 	= 	$filter['keyword'];
	    
	    $lang_js_languages	=	L('js_languages');
	    if ($filter['act_range'] == FAR_ALL){
	        $arr[0] = array(
	            'id'   		=> 	0,
	            'name' 		=>	$lang_js_languages['all_need_not_search']
	        );
	    }
	    elseif ($filter['act_range'] == FAR_CATEGORY){
	        $sql 			= 	"SELECT cat_id AS id, cat_name AS name FROM " . 'ybr_category' .
	            				" WHERE cat_name LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%' LIMIT 50";
	        $arr 			= 	$CommonModel->query($sql);
	    }
	    elseif ($filter['act_range'] == FAR_BRAND){
	        $sql 			= 	"SELECT brand_id AS id, brand_name AS name FROM " . 'ybr_brand' .
	            				" WHERE brand_name LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%' LIMIT 50";
	        $arr 			= 	$CommonModel->query($sql);
	    }
	    else
	    {
	        $sql 			= 	"SELECT goods_id AS id, goods_name AS name FROM " . 'ybr_goods' .
	            				" WHERE goods_name LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%'" .
	            				" OR goods_sn LIKE '%" . Utils::mysql_like_quote($filter['keyword']) . "%' LIMIT 50";
	        $arr = $CommonModel->query($sql);
	    }
	    
	    if (empty($arr)){
	        $arr = array(
	        	0 =>array(
		            'id'   => 0,
		            'name' => L('search_result_empty')
	        	)
	        );
	    }
	    $return['content']	=	$arr;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}
		
	/**
	 * 修改优惠信息
	 * 
	 */
	public function mod_favourable(){
		
		$CommonModel			=	new CommonModel();
	    /* 是否添加 */
	    $this->assign('form_action', 	'update');
	    $this->assign('action', 		'mod_favourable_ok');
	    $this->assign('help_open', 		1);
	
	    /* 初始化、取得优惠活动信息 */
		if (empty($_GET['id'])){
            $this->error("invalid param");
        }
        
        $id 					= 	intval($_GET['id']);
        $favourable 			= 	favourable_info($id);
        if (empty($favourable)){
            //sys_msg($_LANG['favourable_not_exist']);
            $this->error(L('favourable_not_exist'));
        }
	   
	    $this->assign('favourable', $favourable);
	
	    /* 取得用户等级 */
	    $user_rank_list 		= 	array();
	    $user_rank_list[] 		= 	array(
	        'rank_id'   => 0,
	        'rank_name' => L('not_user'),
	        'checked'   => strpos(',' . $favourable['user_rank'] . ',', ',0,') !== false
	    );
	    $sql 					= 	"SELECT rank_id, rank_name FROM " . 'ybr_user_rank';
	    $res 					= 	$CommonModel->query($sql);
	    foreach($res as $row){
	    	$row['checked'] 	= 	strpos(',' . $favourable['user_rank'] . ',', ',' . $row['rank_id']. ',') !== false;
	        $user_rank_list[] 	= 	$row;
	    }
	    
	    $this->assign('user_rank_list', $user_rank_list);
	
	    /* 取得优惠范围 */
	    $act_range_ext = array();
	    if ($favourable['act_range'] != FAR_ALL && !empty($favourable['act_range_ext'])){
	        if ($favourable['act_range'] == FAR_CATEGORY){
	            $sql 			= 	"SELECT cat_id AS id, cat_name AS name FROM " . 'ybr_category' .
	                				" WHERE cat_id " . db_create_in($favourable['act_range_ext']);
	        }
	        elseif ($favourable['act_range'] == FAR_BRAND){
	            $sql = "SELECT brand_id AS id, brand_name AS name FROM " . 'ybr_brand' .
	                " WHERE brand_id " . db_create_in($favourable['act_range_ext']);
	        }
	        else{
	            $sql 			= 	"SELECT goods_id AS id, goods_name AS name FROM " . 'ybr_goods' .
	                				" WHERE goods_id " . db_create_in($favourable['act_range_ext']);
	        }
	        $act_range_ext 		= 	$CommonModel->query($sql);
	    }
	    $this->assign('act_range_ext', $act_range_ext);
		$this->display('favourable_info');
	}
	
	
	/**
	 * 处理修改优惠信息
	 * Enter description here ...
	 */
	public function mod_favourable_ok(){	
		import("@.Plugs.Exchange");
				
		$CommonModel		=	new CommonModel();		
		$exc 				= 	new exchange('ybr_favourable_activity', $CommonModel, 'act_id', 'act_name');
		
	    /* 检查名称是否重复 */
	    $act_name 			= 	sub_str($_POST['act_name'], 255, false);
	    if (!$exc->is_only('act_name', $act_name, intval($_POST['id']))){
	        $this->error(L('act_name_exists'));
	    }
	
	    /* 检查享受优惠的会员等级 */
	    if (!isset($_POST['user_rank'])){
	        //sys_msg($_LANG['pls_set_user_rank']);
	         $this->error(L('pls_set_user_rank'));
	    }
	
	    /* 检查优惠范围扩展信息 */
	    if (intval($_POST['act_range']) > 0 && !isset($_POST['act_range_ext'])){
	    	$this->error(L('pls_set_act_range'));
	    }
	
	    /* 检查金额上下限 */
	    $min_amount 		= 	floatval($_POST['min_amount']) >= 0 ? floatval($_POST['min_amount']) : 0;
	    $max_amount 		= 	floatval($_POST['max_amount']) >= 0 ? floatval($_POST['max_amount']) : 0;
	    if ($max_amount > 0 && $min_amount > $max_amount){
	        //sys_msg($_LANG['amount_error']);
	        $this->error(L('amount_error'));
	    }
	
	    /* 取得赠品 */
	    $gift = array();
	    if (intval($_POST['act_type']) == FAT_GOODS && isset($_POST['gift_id'])){
	        foreach ($_POST['gift_id'] as $key => $id){
	            $gift[] 	= 	array('id' => $id, 'name' => $_POST['gift_name'][$key], 'price' => $_POST['gift_price'][$key]);
	        }
	    }
	
	    /* 提交值 */
	    $favourable = array(
	        'act_id'        => intval($_POST['id']),
	        'act_name'      => $act_name,
	        'start_time'    => local_strtotime($_POST['start_time']),
	        'end_time'      => local_strtotime($_POST['end_time']),
	        'user_rank'     => isset($_POST['user_rank']) ? join(',', $_POST['user_rank']) : '0',
	        'act_range'     => intval($_POST['act_range']),
	        'act_range_ext' => intval($_POST['act_range']) == 0 ? '' : join(',', $_POST['act_range_ext']),
	        'min_amount'    => floatval($_POST['min_amount']),
	        'max_amount'    => floatval($_POST['max_amount']),
	        'act_type'      => intval($_POST['act_type']),
	        'act_type_ext'  => floatval($_POST['act_type_ext']),
	        'gift'          => serialize($gift)
	    );
	    if ($favourable['act_type'] == FAT_GOODS){
	        $favourable['act_type_ext'] 	= 	round($favourable['act_type_ext']);
	    }
	    
	    $CommonModel->autoExecute('favourable_activity', $favourable, 'UPDATE', "act_id = '$favourable[act_id]'");
	    
	    /* 记日志 */
	    admin_log($favourable['act_name'], 'edit', 'favourable');
	
	    /* 清除缓存 
	    clear_cache_files();*/
	
	    /* 提示信息 */		
		$this->success(L('edit_favourable_ok'),U('favourable/favourable_list'));		
	}
	
	/**
	 * 移除优惠信息
	 * Enter description here ...
	 */
	public function remove_favourable(){
		import("@.Plugs.Exchange");
				
		$CommonModel		=	new CommonModel();		
		$exc 				= 	new exchange('ybr_favourable_activity', $CommonModel, 'act_id', 'act_name');
		
	    $id 				= 	intval($_GET['id']);
	    $favourable 		= 	favourable_info($id);
	    if (empty($favourable)){
	        $this->error(L('favourable_not_exist'));
	    }
	    $name 				= 	$favourable['act_name'];
	    $exc->drop($id);
	
	    /* 记日志 */
	    admin_log($name, 'remove', 'favourable');
	
	    /* 清除缓存 
	    clear_cache_files();*/	
	    $this->success("操作成功",U('favourable/favourable_list'));
	}
	
	
	
	
	
}









